import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms#datasets是数据集  transforms是预处理
import numpy as np

batch_size = 200
learning_rate = 0.01
epochs = 10

train_loader = torch.utils.data.DataLoader(
    datasets.MNIST('../../CCV1/week5/data', train=True,download=True,
                   transform=transforms.Compose([
                       transforms.ToTensor(),#先把numpy转成tensor
                       transforms.Normalize((0.1307,), (0.3081,))#标准化一下 按照均值是0.1307 0.3081
                   ])),
    batch_size=batch_size, shuffle=True)#并且定义好batch_size

test_loader = torch.utils.data.DataLoader(
    datasets.MNIST('../../CCV1/week5/data', train=False, transform=transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize((0.1307,), (0.3081,))
    ])),
    batch_size=batch_size, shuffle=True)
#下面分别定义了w和b 用\隔开了
w1, b1 = torch.randn(200, 784, requires_grad=True), \
         torch.zeros(200, requires_grad=True)
w2, b2 = torch.randn(200, 200, requires_grad=True), \
         torch.zeros(200, requires_grad=True)
w3, b3 = torch.randn(10, 200, requires_grad=True), \
         torch.zeros(10, requires_grad=True)
#输出就是10个神经元

# 初始化，对结果影响非常大，未使用该初始化，准确率：10%，使用该初始化，准确率90%左右。
torch.nn.init.kaiming_normal_(w1)
torch.nn.init.kaiming_normal_(w2)
torch.nn.init.kaiming_normal_(w3)


def forward(x):
    x = x @ w1.t() + b1#x和w1相乘，再加上b   上面已经定义好了w1 w2 w3 b1 b2 b3
    x = F.relu(x)#加上激活函数relu
    x = x @ w2.t() + b2#下面也是一样的道理
    x = F.relu(x)
    x = x @ w3.t() + b3
    x = F.relu(x)
    return x#然后返回x

# 未使用relu: 正确率：92%，使用relu:96%
#定义优化器   w1-b3都是要优化的参数  学习率也输入进来
optimizer = optim.SGD([w1, b1, w2, b2, w3, b3], lr=learning_rate)
criteon = nn.CrossEntropyLoss()#损失函数定义的是交叉熵

for epoch in range(epochs):
    #然后就去拿到train_loader里面的数据  batch_idx在上面已经定义好了  batch_size = 200
    for batch_idx, (data, target) in enumerate(train_loader):#通过这个样子去调用数据
        data = data.view(-1, 28 * 28)#然后这个data就是200x28x28的了

        logits = forward(data)#输入数据 然后得到结果 数据应该是200x10
        # logits:预测值，target:ground truth
        loss = criteon(logits, target)#然后算一下loss

        optimizer.zero_grad()
        loss.backward()#要先清0 然后再backward
        # print(w1.grad.norm(), w2.grad.norm())
        # w = w - lr*delta_w
        optimizer.step()#就开始迭代  就是上面的 w = w - lr*delta_w这个方法

        if batch_idx % 100 == 0:#每100次打印一下
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                       100. * batch_idx / len(train_loader), loss.item()))
    #train了一个epoch以后就打印一下loss
    test_loss = 0
    correct = 0
    for data, target in test_loader:
        data = data.view(-1, 28 * 28)
        logits = forward(data)#计算出预测的值
        test_loss += criteon(logits, target).item()

        pred = logits.data.max(1)[1]
        correct += pred.eq(target.data).sum()#然后看一下pred的值和目标的值是不是相等

    test_loss /= len(test_loader.dataset)
    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
        test_loss, correct, len(test_loader.dataset),
        100. * correct / len(test_loader.dataset)))

